<?php


namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class ConfigController extends CommonController
{

    private static $CONFIG_TABLE="sys_config";
    const upload_code=10001; //上传配置编码


    public function SetConf(Request $request){
        $res=$request->all();
        if (!isset($res['upload_status'])){
            return $this->ReturnJson(-1,'参数不完整','');
        }
        $status=$res['upload_status']==1?1:2;
        try {
            DB::beginTransaction();
            DB::table(self::$CONFIG_TABLE)
                ->where('code','=',self::upload_code)
                ->where('status','=',0)
                ->where('delete_flag','=',0)
                ->update(['value'=>json_encode(['upload_status'=>$status]),'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            DB::commit();
            return $this->ReturnJson(200,'保存成功','');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->ReturnJson(-1,$e->getMessage(),'');
        }
    }

    public function GetConf(){
       $res = DB::table(self::$CONFIG_TABLE)
            ->where('status','=',0)
            ->where('delete_flag','=',0)
           ->select('name','code','value','id')
            ->get()
            ->toArray();
       foreach ($res as $k=>$v) {

           switch ($v->code){
               case self::upload_code:
                   $v->value=json_decode($v->value,true);
                   $v->type=EnumController::$upload_map[$v->value['upload_status']];
                   $res['upload_config']=$res[$k];
                   unset($res[$k]);
                   break;
           }
        }
       return $this->ReturnJson(200,'success',$res);
    }

    /**
     * @return mixed
     * 获取上传配置
     */
    public function GetUploadConf(){
        $res=DB::table(self::$CONFIG_TABLE)
            ->where('code','=',self::upload_code)
            ->where('status','=',0)
            ->where('delete_flag','=',0)
            ->select('value')
            ->get()
            ->toArray();
        $res =json_decode($res[0]->value,true);
        return $res['upload_status'];
    }

}
